

package com.iot.spi.core.emqx.contextaware;

import com.iot.spi.core.annotation.Topic;
import com.iot.spi.core.emqx.handler.EmqxProductPackHandler;
import com.iot.spi.core.emqx.handler.NoSupportHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author 21341
 */
@Slf4j
@Service("ProductPackHandlerManagement")
@AllArgsConstructor
public class ProductPackHandlerManagement implements ApplicationContextAware {

    /**
     * 所有实现的包处理器
     */
    private static Map<String, EmqxProductPackHandler> packHandlerMap;

    private NoSupportHandler noSupportHandler;
    /**
     * 唤醒时 初始化 packHandlerMap
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 仅一次性初始化完成 加载解码方法
        if (packHandlerMap == null) {
            packHandlerMap = new ConcurrentHashMap<>(30);
            Map<String, Object> handlers = applicationContext.getBeansWithAnnotation(Topic.class);
            for (Map.Entry<String, Object> entry : handlers.entrySet()) {
                Object handler = entry.getValue();
                if (handler instanceof EmqxProductPackHandler) {
                    Topic topic = handler.getClass().getAnnotation(Topic.class);
                    String key = topic.productCode() + "_" + topic.modelCode();
                    if (topic != null && !packHandlerMap.containsKey(key)) {
                        log.info("add pack handler {} for {}", handler.getClass().getName(), key);
                        packHandlerMap.put(key, (EmqxProductPackHandler) handler);
                    }
                }
            }
        }
    }

    public EmqxProductPackHandler getPackHandler(String modelKey) {
        return packHandlerMap == null ? noSupportHandler : packHandlerMap.get(modelKey.toUpperCase()) == null? noSupportHandler : packHandlerMap.get(modelKey.toUpperCase());
    }
}
